/* Copyright (C) 2010 Luca Piccinelli
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/* 
 * File:   configuration.h
 * Author: picci
 *
 * Created on February 20, 2011, 8:11 PM
 */

#ifndef CONFIGURATION_H
#define	CONFIGURATION_H

#include "prj_definitions.h"
#include "exceptions/factory_exceptions.h"
#include "common/utility_data_structures.h"

#include <string>
#include <map>
#include <vector>
#include <stdexcept>

#include <boost/any.hpp>

namespace NAMESPACE{
  
class ConfigurationTemplate{

protected:
    typedef std::vector<IOKey> set_t;
    set_t params_set;
public:
    ~ConfigurationTemplate();
    ConfigurationTemplate();
    ConfigurationTemplate(const ConfigurationTemplate& ct);
    ConfigurationTemplate& operator=(const ConfigurationTemplate& ct);

    ConfigurationTemplate& add(const IOKey& key);
    const IOKey& param_at(int idx) const throw(std::out_of_range);
    bool contains(const IOKey& key) const;
    size_t parameters_num() const;
};

class Configuration{
public:
    typedef std::map<IOKey, boost::any*> params_map_t;
    
    virtual ~Configuration();
    Configuration();
    Configuration(const Configuration& c);
    Configuration& operator=(const Configuration& c);

    Configuration(const ConfigurationTemplate& ct);

    Configuration& set_template(const ConfigurationTemplate& ct);
    const ConfigurationTemplate& get_template() const;

    template<typename T>
    Configuration& set_parameter(const IOKey& k, const T& value){
        if(ct.contains(k)){;
            if(!(params[k])) {
                params[k] = new boost::any();
            }
            *(params[k]) = value;
        }
        return *this;
    }
    template<typename T>
    T get_parameter(const IOKey& k) const throw(bad_parameter){
        if(ct.contains(k)){
            const boost::any* param_container = params.at(k);
            if(!param_container) return T();
            try{
                return boost::any_cast<T>(*param_container);
            }catch(boost::bad_any_cast& ex){
                throw bad_parameter(ex.what());
            }
        }
        throw bad_parameter("No such parameter defined:" + k.get_key());
    }
    
    const params_map_t& get_all_params() const;
    
protected:
    ConfigurationTemplate ct;
    params_map_t params;
};

}

#endif	/* CONFIGURATION_H */

